<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Models\CartModel;
use App\Utils\ControllerModelTrait;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CartController extends ApiController
{
    use ControllerModelTrait;

    /**
     * 获取用户购物车
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getList(Request $request): JsonResponse
    {
        $uid = $this->verifyId('uid', 0);
        $paginate = $this->getPagedData(CartModel::where('uid', $uid), $request);
        $items = $paginate->items();
        $data = groupGoodsData(json_decode(json_encode($items), true), true, 'goods_info', ['goods_num', 'goods_id']);
        return $this->success($this->getPaginate($paginate, $data));
    }

    /**
     * 网页购物车列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getWebList(Request $request): JsonResponse
    {
		$uid = $request->input('uid', 0);
        $collection = CartModel::where('uid', $uid)->select(['goods_info', 'goods_num', 'goods_id'])
            ->orderByDesc('id')->take(100)->get()->each(function ($item) {
                $goodsInfo = json_decode($item->goods_info, true);
                if ($goodsInfo)
                    $goodsInfo['goods_num'] = $item->goods_num;
                $item->goods_info = $goodsInfo;
                return $item;
            });
		return $this->success($collection);
    }

    /**
     * 添加购物车
     * @param Request $request
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doSave(Request $request): JsonResponse
    {
        $uid = $this->verifyId('uid');
        $goodsSpecData = $this->verifyString('goods_spec');
        $goods_id = $this->verifyInteger('goods_id');
        $goodsSpecs = json_decode($goodsSpecData, true);
        if ($goodsSpecs) {
            foreach ($goodsSpecs as $v) {
                $cart = CartModel::where('uid', $uid)->where('goods_sn', $v['goods_sn'])->first();
                if ($cart) {
                    $cart->goods_num = $v['goods_num'] + $cart->goods_num;
                    $cart->save();
                }  else {
                    if ($v['goods_num'])
                        CartModel::addCart($uid, $goods_id, $v);
                }
            }
        }
        return $this->success();
    }


    /**
     * 移除购物车
     * @return JsonResponse
     * @throws BusinessException
     */
    public function doDelete(): JsonResponse
    {
        $uid = $this->verifyId('uid');
        $goods_sn = $this->verifyString('goods_sn');
        $goodsSnArray = explode(',', $goods_sn);
        CartModel::whereIn('goods_sn', $goodsSnArray)->where('uid', $uid)->delete();
        return $this->success();
    }
}
